#! /usr/bin/env bash

bssid=$1
essid=$2

if [ -z "$bssid" ]
then
	echo Usage: $(basename $0) bssid [essid]
	exit
fi

cd "$(dirname "$0")"
cd ..

identifier=$(echo $bssid | tr '[A-Z]' '[a-z]' | tr --delete ':')
if [ ! -z "$essid" ]
then
	identifier=$identifier-$(echo $essid | tr '[A-Z]' '[a-z]' | tr --complement --delete '[a-z0-9]')
fi

cap=capture/$identifier/????-??-??-??-??-??-??.cap
if ls $cap &> /dev/null
then
	list=$(ls -1 $cap | sed 's/\.cap$/.ivs/m')
	while read ivs
	do
		if [ ! -f $ivs ]
		then
			cap=$(echo $ivs | sed 's/\.ivs$/.cap/')
			echo $(date +"%Y-%m-%d %H:%M:%S") Indexing capture $(basename $ivs | sed 's/^\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\)\.ivs$/\1 \2:\3:\4 \5/')
			ivstools --convert $cap $ivs > /dev/null

			if [ ! -f $ivs ]
			then
				cp script/empty.ivs $ivs
			fi
		fi
	done <<< "$list"
fi

ivs=capture/$identifier/????-??-??-??-??-??-??.ivs
if ls $ivs &> /dev/null
then
	ivstools --merge $ivs capture/$identifier/capture.ivs > /dev/null
fi

